package com.sky.service.common.imp;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.operator.InList;
import com.ejlchina.searcher.util.MapUtils;
import com.sky.common.File;
import com.sky.exception.ServiceException;
import com.sky.mapper.FileMapper;
import com.sky.service.common.IFileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * 文件
 *
 * @author tzl
 * @date 2023/1/18
 */
@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, File> implements IFileService
{
    @Resource
    private FileMapper fileMapper;
    @Resource
    private BeanSearcher beanSearcher;

    @Value("${file-ip}")
    private String fileIp;

    /**
     * 查询文件记录
     *
     * @param fileIds 文件ids
     * @return 结果
     */
    @Override
    public List<File> selectFiles(String fileIds) {
        List<File> files = beanSearcher.searchAll(File.class, MapUtils.builder()
                .field(File::getId, (Object[]) fileIds.split(",")).op(InList.class)
                .build());

        for (File file : files) {
            file.setPath(fileIp + file.getPath());
        }
        return files;
    }

    /**
     * 查询文件记录
     *
     * @param fileIds 文件ids
     * @return 结果
     */
    @Override
    public List<File> selectFilesUrl(String fileIds) {

        return beanSearcher.searchAll(File.class, MapUtils.builder()
                .field(File::getId, (Object[]) fileIds.split(",")).op(InList.class)
                .build());
    }

    /**
     * 保存文件记录
     *
     * @param files 文件
     * @return 文件ids
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String saveFiles(List<File> files) {
        if (!saveBatch(files)) {
            throw new ServiceException("保存文件记录失败");
        }

        StringBuilder fileIds = new StringBuilder();
        for (File file : files) {
            fileIds.append(file.getId()).append(",");
        }
        fileIds.deleteCharAt(fileIds.length() - 1);

        return fileIds.toString();
    }

    @Override
    public String saveFile(File file) {
        Objects.requireNonNull(file);
        fileMapper.insert(file);
        return String.valueOf(file.getId());
    }
}
